﻿using BW.EatRabbit.API.Application.Commands.Cities;
using BW.EatRabbit.API.Dtos;
using BW.EatRabbit.Domain;
using BW.EatRabbit.ErrorCode;
using BW.EatRabbit.Infrastructure.Interfaces;
using MediatR;

namespace BW.EatRabbit.API.Application.CommandHandlers.Cities
{
    public class GetCitiesQueryCommandHandler : IRequestHandler<GetCitiesQueryCommand, APIResult<List<CityDTO>>>
    {
        private readonly IBaseRepository<Province_Information> _provinceRepository;
        private readonly IBaseRepository<City_Information> _cityRepository;
        private readonly IBaseRepository<ProvinceCity> _provincecityRepository;
        public GetCitiesQueryCommandHandler(IBaseRepository<Province_Information> provinceRepository, IBaseRepository<City_Information> cityRepository, IBaseRepository<ProvinceCity> provincecityRepository)
        {
            _provinceRepository = provinceRepository;
            _cityRepository = cityRepository;
            _provincecityRepository = provincecityRepository;

        }
        public Task<APIResult<List<CityDTO>>> Handle(GetCitiesQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<CityDTO>> result = new APIResult<List<CityDTO>>();

            var ment = from a in _provinceRepository.GetAll()
                       join b in _provincecityRepository.GetAll() on a.ProvinceId equals b.ProvinceId
                       join c in _cityRepository.GetAll() on b.CityId equals c.CityId
                       where a.ProvinceId == request.ProvinceId
                       select new CityDTO
                       {
                           PCId=b.PCId,
                           ProvinceId=a.ProvinceId,
                           ProvinceName=a.ProvinceName,
                           CityId=c.CityId,
                           CityName=c.CityName,


                       };
            if(ment == null)
            {
                result.Code = ResultCode.查询失败;
                result.Message = ResultCode.查询失败.ToString();
            }
            result.Code = ResultCode.查询成功;
            result.Message = ResultCode.查询成功.ToString();
            result.Data = ment.ToList();

            return Task.FromResult(result);


        }
    }
}
